package com.fire.web.modules.all.service.impl;

import com.fire.common.utils.StringUtils;
import com.fire.core.util.DateUtil;
import com.fire.web.modules.all.entity.AssetCategoryModel;
import com.fire.web.modules.all.service.IAssetCategoryService;
import com.fire.web.modules.all.service.IAssetService;
import com.fire.web.modules.all.validation.AssetDTO;
import com.smartthing.rest.model.asset.AssetCategory;
import com.smartthing.rest.model.asset.LocationAsset;
import com.smartthing.rest.model.asset.request.AssetCategoryCreateRequest;
import com.smartthing.rest.model.device.Device;
import com.smartthing.rest.model.device.DeviceAssignment;
import com.smartthing.rest.model.device.request.LocationAssetCreatRequest;
import com.smartthing.rest.model.search.AssetSearchResults;
import com.smartthing.rest.model.search.DeviceAssignmentSearchResults;
import com.smartthing.rest.model.search.SearchCriteria;
import com.smartthing.spi.ISmartThingClient;
import com.smartthing.spi.SmartThingException;
import com.smartthing.spi.asset.AssetType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName: AssetServiceImpl
 * @Description: TODO
 * @Author raoyuxing
 * @Date 2019/1/14 18:43
 */
@Service
public class AssetServiceImpl implements IAssetService {

    @Autowired
    private ISmartThingClient client;

    @Autowired
    private IAssetCategoryService categoryService;

    /**
     * 功能描述: 新增资产
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/18 9:58
     */
    @Override
    public LocationAsset addAsset(AssetDTO assetDTO) throws SmartThingException {

        AssetCategoryModel categoryModel = categoryService.selectById(assetDTO.getAssetcategoryid());

        String categroyId = checkCategory(assetDTO.getSiteid());
        LocationAssetCreatRequest request = new LocationAssetCreatRequest();
        request.setId(UUID.randomUUID().toString());
        request.setImageUrl(categoryModel.getCategoryurl());
        request.setName(categoryModel.getCategoryname());
        request.setLatitude(0D);
        request.setLongitude(0D);
        request.setElevation(0D);

        String arange ;
        if (categoryModel.getLevel() == 1){
            arange = "outroom";
        }else if (categoryModel.getLevel() == 2){
            arange = "inroom";
        }else if (categoryModel.getLevel() == 3){
            arange = "autospring";
        }else if (categoryModel.getLevel() == 4){
            arange = "gasfire";
        }else if (categoryModel.getLevel() == 5){
            arange = "foamfire";
        }else if (categoryModel.getLevel() == 6){
            arange = "autoalarm";
        }else if (categoryModel.getLevel() == 7){
            arange = "ejectsmoke";
        }else if (categoryModel.getLevel() == 8){
            arange = "smokeprevention";
        }else if (categoryModel.getLevel() == 9){
            arange = "keypart";
        }else {
            arange = "other";
        }

        Map<String,Object> map = new HashMap<>();
        map.put("assetcategoryid",categoryModel.getCategoryid());
        map.put("sitetoken",assetDTO.getSiteid());
        map.put("Alocation",assetDTO.getAlocation());
        map.put("Arange",arange);
        map.put("createtime",DateUtil.getTime(new Date()));
        request.setProperties(map);

        LocationAsset result = client.createLocationAsset(categroyId,request);

        return result;
    }

    /**
     * 功能描述: 获取资产列表
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/18 9:58
     */
    @Override
    public AssetSearchResults getAssetList(AssetDTO assetDTO) throws SmartThingException {
        String categroyId = checkCategory(assetDTO.getSiteid());
        SearchCriteria criteria = new SearchCriteria(assetDTO.getPage(),assetDTO.getPagesize());
//        String categroyId = "localtion@bb105f8d-3150-41f5-b9d1-db04965668d3";
//        SearchCriteria criteria = new SearchCriteria(1,100);
        AssetSearchResults results = client .getAssetsByCategoryId(categroyId,criteria);
        return results;
    }

    /**
     * 功能描述: 查询资产详情
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/18 9:58
     */
    @Override
    public LocationAsset getAssetDetail(AssetDTO assetDTO) throws SmartThingException {
        String categroyId = checkCategory(assetDTO.getSiteid());
        LocationAsset result = client .getLocationAssetDetails(categroyId,assetDTO.getAssetid());
        return result;
    }

    /**
     * 功能描述: 根据sitetoken获取资产列表
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/21 14:20
     */
    @Override
    public Map getAssetListBySiteId(AssetDTO assetDTO) throws SmartThingException {
        SearchCriteria criteria = new SearchCriteria(assetDTO.getPage(),assetDTO.getPagesize());
//        SearchCriteria criteria = new SearchCriteria(1,100);
        DeviceAssignmentSearchResults results = client .listAssignmentsForSite(assetDTO.getSiteid(),null,
                true,true,false,criteria);
        List list = new ArrayList();
        for (DeviceAssignment assignment: results.getResults()){
            Map map = new HashMap();
            map.put("moduleid",assignment.getAssetModuleId());
            map.put("assetid",assignment.getAssetId());
            map.put("assetname",assignment.getAssetName());
            map.put("assetimageurl",assignment.getAssetImageUrl());
            map.put("createtime", DateUtil.format(assignment.getCreatedDate()));
            map.put("Alocation",assignment.getMetadata("Alocation"));
            map.put("Arange",assignment.getMetadata("Arange"));
            map.put("location",assignment.getMetadata("location"));
            Device device = assignment.getDevice();
            if (device != null){
                map.put("deviceid",device.getHardwareId());
                map.put("assignmentToken",device.getAssignmentToken());
                map.put("deviceimageurl",device.getAssetImageUrl());
                map.put("devicename", device.getAssetName().replace("zichang",""));
            }
            list.add(map);
        }
        Map map = new HashMap();
        map.put("assignedlists",list);
        map.put("total",results.getNumResults());
        return map;
    }

    /**
     * 功能描述: 获取消防资产类型列表
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/21 14:20
     */
    @Override
    public Map bindFacilitiesList(AssetDTO assetDTO) throws SmartThingException {
        SearchCriteria criteria = new SearchCriteria(assetDTO.getPage(),assetDTO.getPagesize());
//        SearchCriteria criteria = new SearchCriteria(1,100);
        DeviceAssignmentSearchResults results = client .listAssignmentsForSite(assetDTO.getSiteid(),null,
                false,false,false,criteria);
        List list = new ArrayList();
        for (DeviceAssignment assignment: results.getResults()){
            Map map = new HashMap();
            map.put("moduleid",assignment.getAssetModuleId());
            map.put("assetid",assignment.getAssetId());
            map.put("assetname",assignment.getAssetName());
            map.put("assetimageurl",assignment.getAssetImageUrl());
            map.put("createtime", DateUtil.format(assignment.getCreatedDate()));
            map.put("Alocation",assignment.getMetadata("Alocation"));
            map.put("Arange",assignment.getMetadata("Arange"));
            if (StringUtils.isNotBlank(assetDTO.getArange()) &&
                    assetDTO.getArange().equals(assignment.getMetadata("Arange"))) {
                list.add(map);
            }
        }
        Map map = new HashMap();
        map.put("assignedlists",list);
        map.put("total",list.size());
        return map;
    }

    /**
     * 功能描述: 获取消防资产类型列表（未绑定）
     *
     * @param assetDTO
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/21 14:20
     */
    @Override
    public AssetSearchResults facilitiesList(AssetDTO assetDTO) throws SmartThingException {
        String categroyId = checkCategory(assetDTO.getSiteid());
        SearchCriteria criteria = new SearchCriteria(assetDTO.getPage(),assetDTO.getPagesize());
//        String categroyId = "localtion@bb105f8d-3150-41f5-b9d1-db04965668d3";
//        SearchCriteria criteria = new SearchCriteria(1,100);
        AssetSearchResults results = client.getAssetsByCategoryIdAndArange(categroyId,assetDTO.getArange(),criteria);
        return results;
    }

    /**
     * 功能描述: 条件查询资产列表
     *
     * @param assetDTO
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/18 9:58
     */
    @Override
    public AssetSearchResults getSearchAssetList(AssetDTO assetDTO) throws SmartThingException {
        String categroyId = checkCategory(assetDTO.getSiteid());
        AssetSearchResults results = client.searchAssets(categroyId,assetDTO.getName());
        return results;
    }

    /**
     * 功能描述: 删除资产
     *
     * @param assetDTO
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/21 14:20
     */
    @Override
    public AssetSearchResults deleteAsset(AssetDTO assetDTO) throws SmartThingException {
        String categroyId = checkCategory(assetDTO.getSiteid());
        AssetSearchResults results = client.deleteCategoryAsset(categroyId,assetDTO.getAssetid());
        return results;
    }

    /**
     * 功能描述: 修改资产
     *
     * @param assetDTO
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/21 14:20
     */
    @Override
    public LocationAsset updateAsset(AssetDTO assetDTO) throws SmartThingException {

        String categroyId = checkCategory(assetDTO.getSiteid());
        LocationAssetCreatRequest request = new LocationAssetCreatRequest();
        request.setId(assetDTO.getAssetid());
        request.setImageUrl(assetDTO.getSpotimage());
        request.setName(assetDTO.getName());
        request.setLatitude(Double.valueOf(assetDTO.getLatitude()));
        request.setLongitude(Double.valueOf(assetDTO.getLongitude()));
        request.setElevation(Double.valueOf(assetDTO.getElevation()));

        Map<String,Object> map = new HashMap<>();
        map.put("assetcategoryid",categroyId);
        map.put("sitetoken",assetDTO.getSiteid());
        map.put("Alocation",assetDTO.getAlocation());
        map.put("Arange",assetDTO.getArange());
        map.put("createtime",assetDTO.getCreatetime());
        request.setProperties(map);

        LocationAsset result = client.updateLocationAsset(categroyId,assetDTO.getAssetid(),request);
        return result;
    }


    public String checkCategory(String siteid) throws SmartThingException{

        String categoryId = "localtion@" + siteid;
        AssetCategory category = client.getCatrgory(categoryId);
        if (category != null){
            return category.getId();
        }

        AssetCategoryCreateRequest request = new AssetCategoryCreateRequest();
        request.setId(categoryId);
        request.setName("location@" + System.currentTimeMillis());
        request.setAssetType(AssetType.Location);
        AssetCategory assetCategory = client.creatAssetsCategories(request);
        return assetCategory.getId();
    }
}
